package com.thinkgem.jeesite.modules.sys.webservice;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.thinkgem.jeesite.common.mapper.JaxbMapper;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.common.web.webservice.Request;
import com.thinkgem.jeesite.common.web.webservice.Response;
import com.thinkgem.jeesite.common.web.webservice.ResponseState;
import com.thinkgem.jeesite.modules.sys.exception.WebServiceException;
import com.thinkgem.jeesite.modules.sys.helper.TerminalServiceHelper;

@Controller
@RequestMapping(value = "/terminal")
public class TerminalRequestController {

	//private XmlMapper mapper = new XmlMapper();
	private static Logger mlogger = Logger.getLogger(TerminalRequestController.class);
	private static final List<String> ignoreRequest = new ArrayList<String>();
	private static final String errorMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response><responseState><code>99</code><description>服务器发生未知异常!</description></responseState></response>";
	private static final String permissionDenied = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response><responseState><code>4</code><description>当前登录用户已过期，请重新登录!</description></responseState></response>";

	public TerminalRequestController() {
		ignoreRequest.add("1000");
	}

	/**
	 * 处理请求
	 * 
	 * @param data
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/handle")
	public @ResponseBody
	String handleRequest(HttpServletRequest request, @RequestBody String data) {
		mlogger.debug("requestXml:" + data);
		String requestCode = null;
		Response<?> invokeResult = new Response();
		String responseStr = null;
		try {
			Document dc = DocumentHelper.parseText(data);
			Element root = dc.getRootElement();
			Element requestInfo = root.element("requestParam");
			Element requestData = root.element("data");
			Element pagingData = root.element("pagingInfo");
			requestCode = requestInfo.element("handlerType").getText();
			boolean isIgnore = ignoreRequest.contains(requestCode);
			boolean hasPermission = isIgnore || checkPermission(requestInfo);
			if (hasPermission) {
				TerminalServiceHelper instance = TerminalServiceHelper.getInstance();
				String serviceName = instance.getService(requestCode);
				IBaseWebserviceService<Request> baseWebserviceService = SpringContextHolder.getBean(serviceName);
				responseStr = baseWebserviceService.dealSubmit(request, requestData, pagingData);
			} else {
				return permissionDenied;
			}
			return responseStr;
		} catch (DocumentException e) {
			invokeResult.setStateCode(ResponseState.CODE.XML_FORMAT_EXCEPTION);
			invokeResult.getResponseState().addError("请求报文格式错误");
			try {
				return writeValueAsBytes(invokeResult);
			} catch (Exception e1) {
				mlogger.error("webservice error:", e);
				return errorMsg;
			}
		} catch (InvocationTargetException e) {
			if (e.getTargetException() instanceof WebServiceException) {
				WebServiceException ex = (WebServiceException) e.getTargetException();
				invokeResult.setStateCode(ex.getExceptionCode());
				invokeResult.getResponseState().addError(ex.getMessage());
				try {
					return writeValueAsBytes(invokeResult);
				} catch (Exception e1) {
					mlogger.error("webservice error:", e);
					return errorMsg;
				}
			}
			mlogger.error("webservice error:", e);
			return errorMsg;
		} catch (InvalidFormatException e){
			invokeResult.setStateCode(ResponseState.CODE.PARAM_FORMAT_EXCEPTION);
			invokeResult.getResponseState().addError("参数传递格式错误");
			try {
				return writeValueAsBytes(invokeResult);
			} catch (Exception e1) {
				mlogger.error("webservice error:", e);
				return errorMsg;
			}
		}catch (WebServiceException e){
			invokeResult.setStateCode(e.getExceptionCode());
			invokeResult.getResponseState().addError(e.getMessage());
			try {
				return writeValueAsBytes(invokeResult);
			} catch (Exception e1) {
				mlogger.error("webservice error:", e);
				return errorMsg;
			}
		}catch (Exception e) {
			mlogger.error("webservice error:", e);
			return errorMsg;
		}
	}


	private boolean checkPermission(Element srequestInfo) {
		return true;
	}

	private String writeValueAsBytes(Response<?> invokeResult) throws Exception {
		String result = null;
		result = JaxbMapper.toXml(invokeResult);
		mlogger.info("responseXml:" + result);
		return result;
	}
}
